package com.qf.service.impl;

import com.google.common.cache.LoadingCache;
import com.qf.cache.SceneCache;
import com.qf.exeptions.AddDataException;
import com.qf.exeptions.DeleteDataException;
import com.qf.exeptions.ResultCode;
import com.qf.mappers.SceneMapper;
import com.qf.pojo.CheckType;
import com.qf.pojo.Scene;
import com.qf.pojo.User;
import com.qf.service.SceneService;
import com.qf.utils.SecurityUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

/*
杨威
2022/1/2
16:15
*/
@Service
@Transactional
public class SceneServiceImpl implements SceneService {
    @Autowired
    private SceneMapper sceneMapper;
    @Autowired
    private SceneCache sceneCache;
    @Override
    public void addScene(Scene scene) {
        Assert.isTrue(!scene.isEmpty(CheckType.ADD),()->{
            throw new AddDataException("数据不完整", ResultCode.DATA_EMPTY);
        });
        User user = SecurityUtils.getUser();
        Scene scene1 = sceneMapper.selectByUserIdAndName(user.getUId(), scene.getSceneName());
        Assert.isTrue(scene1==null||scene1.getStatus()!=1,()->{
            throw new AddDataException("场景已经存在",ResultCode.DATA_ALREADY_EXIST);
        });

        if(scene1==null){//新增数据
            scene.setCreateBy(user.getUId());
            scene.setCreateTime(new Date());
            sceneMapper.addScene(scene);
        }else {//修改数据
            sceneMapper.reEnableScene(scene1.getSceneId(),new Date());
        }


    }

    @Override
    public void updateScene(Scene scene) {
        Assert.isTrue(scene.isEmpty(CheckType.UPDATE),()->{
            throw new AddDataException("数据不能为空",ResultCode.DATA_EMPTY);
        });
        sceneMapper.updateScene(scene);
        sceneCache.getSceneLoadingCache().invalidateAll();//清理缓存
    }

    @Override
    public int deleteByIds(List<Long> ids) {
        Assert.notEmpty(ids,()->{
            throw new DeleteDataException("数据不完整",ResultCode.DATA_EMPTY);
        });
        User user = SecurityUtils.getUser();
        sceneCache.getSceneLoadingCache().invalidateAll();//清理缓存
        return sceneMapper.deleteScenesByIdsAndUid(ids, user.getUId());
    }

    @Override
    public List<Scene> findByUserId(Long userId) {
        List<Scene> sceneList;
        try {
            sceneList = sceneCache.getSceneLoadingCache().get(userId);
            return sceneList;
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
